<?php

namespace app\mall\controller;

use app\controller\ZipArchive;

class UpgradeController
{
    public function index()
    {
        //获取版本更新信息
        $server = json_encode([
            'version' => 20210203,
            'desc'    => 'BUG修正，缓存系统',
            'files'   => 'https://test.com/api/data/20210203.zip',
            'schemas' => '',//数据库升级文件
        ]);

        //多个升级包,依次更新

        $begin = microtime(true);
        //检查更新,加载本地版本号
        $config = ['version' => '20210203'];



        echo '连接更新服务器...<br/>';
        $upgrade = json_decode(file_get_contents($server), true);

        if (!isset($versions['version'][$config['version']])) {
            echo '当前已是最新版本!';
        } else {
            //下载并解压文件
            echo '当前版本：<b>', $config['version'], '</b> 服务器版本：<b>', $upgrade['version'], '</b><br/>';

            //开始下载
            $remote_fp = fopen($upgrade['files'], 'rb');
            if(!is_dir(__DIR__.'/upgrade')) mkdir(__DIR__.'/upgrade');
            $tmp = __DIR__ . '/upgrade/' . date('YmdHis') . '.zip';
            $local_fp = fopen($tmp, 'wb');
            echo '开始下载...<br/>';
            while (!feof($remote_fp)) {
                fwrite($local_fp, fread($remote_fp, 128));
            }
            fclose($remote_fp);
            fclose($local_fp);

            echo '下载完成,准备解压<br/>';
            $zip = new ZipArchive();
            if ($zip->open($tmp) === true) {
                $zip->extractTo(__DIR__);
                $zip->close();
            }

            echo '解压完成,准备删除临时文件<br/>';
            //删除补丁包
            unlink($tmp);
            echo '临时文件删除完毕<br/>';

            // 运行数据库升级
            if (!empty($upgrade['schemas'])) {
                $upgrade['schemas'];
            }

            //更新本地版本号
            $content = file_get_contents(__DIR__.'/config.php');
            $content = str_replace($config['version'], $upgrade['version'], $content);
            file_put_contents(__DIR__.'/config.php',$content);
            echo '更新完成!耗时',microtime(true) - $begin,'秒<br/>';
            exit();
        }

    }


}